#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <pthread.h>
#include <signal.h>

#include "err_handing.h"
#include "read_child.h"

#define BUF_SIZE 256

int main(int argc, char *argv[])
{
    int sock;
    char msg_recv[BUF_SIZE], msg_send[BUF_SIZE];
    struct sockaddr_in serv_addr;
    pid_t pid;
    struct sigaction act;
    act.sa_handler = read_childproc;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGCHLD, &act, NULL);
    int recv;
    if (argc != 3)
    {
        printf("Usage :%s <ip> <port>\n", argv[0]);
        exit(0);
    }

    sock = socket(PF_INET, SOCK_STREAM, 0);

    memset(&serv_addr, 0, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
    serv_addr.sin_port = htons(atoi(argv[2]));

    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) == -1)
        error_handling("connect() error");

    pid = fork();
    if (pid == -1)
        error_handling("fork() error");
    if (pid == 0)
    {
        while (1)
        {
            fgets(msg_send, BUF_SIZE, stdin);
            // if (!strcmp(msg_send, "q\n") || !strcmp(msg_send, "Q\n"))
            // {
            //     shutdown(sock,SHUT_WR);
            //     break;
            // }
            recv = write(sock, msg_send, 256);
            if (recv == -1)
                error_handling("write() error");
        }
    }
    else
    {
        // close(sock);
        while (1)
        {
            recv = read(sock, msg_recv, 256);
            if (recv == 0)
            {
                // printf("read() error");
                close(sock);
                printf("You typed Q to disconnected\n");
                break;
            }
            printf(">>>message from server:%s",msg_recv);
        }
    }
    close(sock);
    return 0;
}